#include "socket.h"

struct socket * new_socket( char *server_name, char *port ) 
{
	struct socket *socket_t;

	/* Okay, here I became very lazy, look at the man page of gettaddrinfo */
		
	struct addrinfo hints;
	struct addrinfo *result, *rp;
	int sfd, s;

	/* Obtain address(es) matching host/port */

	memset(&hints, 0, sizeof(struct addrinfo));
	hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
	hints.ai_socktype = SOCK_STREAM; /* Stream socket */
	hints.ai_flags = 0;
	hints.ai_protocol = 0;          /* Any protocol */

	s = getaddrinfo(server_name, port, &hints, &result);
	if (s != 0) {
		 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
		 return NULL;
	}

	/* getaddrinfo() returns a list of address structures.
		Try each address until we successfully connect(2).
		If socket(2) (or connect(2)) fails, we (close the socket
		and) try the next address. */

	for (rp = result; rp != NULL; rp = rp->ai_next) {
		 sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
		 if (sfd == -1)
			   continue;

		 if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
			   break;                  /* Success */

		 close(sfd);
	}

	if (rp == NULL) {               /* No address succeeded */
		fprintf(stderr, "Could not connect to %s\n", server_name);
		freeaddrinfo(result);
		return NULL;
	}

	freeaddrinfo(result);           /* No longer needed */

	/* man page copy ends... */

	socket_t = (struct socket*) malloc( sizeof( struct socket ) );

	if ( socket_t == NULL )
		return NULL;

	socket_t->server_name = server_name;
	socket_t->port = atoi( port );
	socket_t->sockfd = sfd;

	return socket_t;
}

void delete_socket( struct socket *socket_t ) 
{
	if ( socket_t != NULL ) {
		printf("Deleting socket %d \n", socket_t->sockfd);
		close( socket_t->sockfd );
		free( socket_t );
	}
}
